package hk.m4s.lr.repair.test.ui.equipment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.bumptech.glide.Glide;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import framework.common.Constant;
import framework.common.alertview.AlertView;
import framework.common.alertview.OnItemClickListener;
import framework.common.baseui.UeBaseActivity;
import framework.common.takephoto.CustomHelper;
import framework.common.zanetwork.core.ResponseCallback;
import framework.common.zanetwork.core.UploadCallback;
import framework.common.zanetwork.core.UploadHelper;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.DeviceModel;
import hk.m4s.lr.repair.test.model.DeviceModelResult;
import hk.m4s.lr.repair.test.service.device.DeviceListervice;
import hk.m4s.lr.repair.test.service.user.MyService;
import hk.m4s.lr.repair.test.ui.adapter.EquipmentListAdapter;
import hk.m4s.lr.repair.test.ui.adapter.UserDeviceAdapter;
import hk.m4s.lr.repair.test.utils.FileUtils;
import hk.m4s.lr.repair.test.utils.NetWorkUtil;
import hk.m4s.lr.repair.test.views.listview.InnerListView;
import hk.m4s.lr.repair.test.views.listview.VListView;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/3/22.
 * 设备台账详情
 */

public class MyEquipmentDetailActivity extends UeBaseActivity implements View.OnClickListener, OnItemClickListener {
    private VListView vlist;
    private List<DeviceModel> list = new ArrayList<DeviceModel>();
    private EquipmentListAdapter equipmentListAdapter;
    private RelativeLayout jieshao_lay, jishu_lay, shiyong_lay, yanghu_lay;
    private RelativeLayout jieshao_detail, complain_click_area, yanghu_click_area,shiyong_click_area, jishu_detail, shiyong_detail, yanghu_detail;
    private ImageView jieshao_nor, complain_add_video, complain_status_btn,yanghu_add_video, yanghu_status_btn, jishu_nor, shiyong_nor, yanghu_nor, equiment_img, shiyong_img, shiyong_add_video, shiyong_status_btn;
    private TextView equ_number, shiyong_text, yanghu_text,jishu_text;
    private Context context;
    private InnerListView listview;
    private int pageNum = 0;
    private int pageSize = 10;
    private int jieState = 0;
    private int jishuState = 0;
    private int shiyongState = 0;
    private int yanghuState = 0;
    private DeviceModel deviceModel;
    private Handler handler = null;
    private ArrayList<TImage> imgList;
    private String logo = "";
    private int alert=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.acyivity_equipment_detaile);
        context = this;
        handler = new Handler();
        hiddenFooter();
        showGoBackBtn();
        setRightText("上传图片");

        setTitleText("设备台账");
        deviceModel = (DeviceModel) getIntent().getSerializableExtra("deviceModel");
        getRightTextView().setOnClickListener(this);
        findBaseView();
    }

    private void findBaseView() {
        jieshao_lay = (RelativeLayout) findViewById(R.id.jieshao_lay);
        jishu_lay = (RelativeLayout) findViewById(R.id.jishu_lay);
        shiyong_lay = (RelativeLayout) findViewById(R.id.shiyong_lay);
        yanghu_lay = (RelativeLayout) findViewById(R.id.yanghu_lay);
        jieshao_detail = (RelativeLayout) findViewById(R.id.jieshao_detail);
        jishu_detail = (RelativeLayout) findViewById(R.id.jishu_detail);
        shiyong_detail = (RelativeLayout) findViewById(R.id.shiyong_detail);
        yanghu_detail = (RelativeLayout) findViewById(R.id.yanghu_detail);
        complain_click_area = (RelativeLayout) findViewById(R.id.complain_click_area);
        shiyong_click_area = (RelativeLayout) findViewById(R.id.shiyong_click_area);
        yanghu_click_area = (RelativeLayout) findViewById(R.id.yanghu_click_area);
        jieshao_nor = (ImageView) findViewById(R.id.jieshao_nor);
        jishu_nor = (ImageView) findViewById(R.id.jishu_nor);
        shiyong_nor = (ImageView) findViewById(R.id.shiyong_nor);
        complain_add_video = (ImageView) findViewById(R.id.complain_add_video);
        complain_status_btn = (ImageView) findViewById(R.id.complain_status_btn);
        shiyong_add_video = (ImageView) findViewById(R.id.shiyong_add_video);
        shiyong_status_btn = (ImageView) findViewById(R.id.shiyong_status_btn);
        yanghu_add_video = (ImageView) findViewById(R.id.yanghu_add_video);
        yanghu_status_btn = (ImageView) findViewById(R.id.yanghu_status_btn);
        yanghu_nor = (ImageView) findViewById(R.id.yanghu_nor);
        equiment_img = (ImageView) findViewById(R.id.equiment_img);
        equ_number = (TextView) findViewById(R.id.equ_number);
        shiyong_text = (TextView) findViewById(R.id.shiyong_text);
        yanghu_text = (TextView) findViewById(R.id.yanghu_text);
        listview= (InnerListView) findViewById(R.id.jishu_text);
        complain_click_area.setOnClickListener(this);
        shiyong_click_area.setOnClickListener(this);
        yanghu_click_area.setOnClickListener(this);
        jieshao_lay.setOnClickListener(this);
        jishu_lay.setOnClickListener(this);
        shiyong_lay.setOnClickListener(this);
        yanghu_lay.setOnClickListener(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    handler.post(runnableUi);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
        equ_number.setText(Html.fromHtml(deviceModel.getInfo()));
        shiyong_text.setText(Html.fromHtml(deviceModel.getUseInfo()));
        yanghu_text.setText(Html.fromHtml(deviceModel.getMaintenanceInfo()));
         List<Map>list=new ArrayList<>();
        try {
            if(!deviceModel.getPropertyJson().equals("")) {
                JSONObject obj = new JSONObject(deviceModel.getPropertyJson());
                Iterator it = obj.keys();
                while (it.hasNext()) {
                    Map<String, String> map = new HashMap();
                    String key = (String) it.next();
                    String value = obj.getString(key);
                    map.put("name", key);
                    map.put("content", value);
                    list.add(map);
                }
                UserDeviceAdapter adpter = new UserDeviceAdapter(context, list);
                listview.setAdapter(adpter);
            }
            if (!(deviceModel.getDeviceLogo() == null || deviceModel.getDeviceLogo().equals(""))) {
                equiment_img.setVisibility(View.VISIBLE);
                Glide.with(context).load(deviceModel.getDeviceLogo()).asBitmap().error(R.mipmap.device_list_no_img).into(equiment_img);
            } else {
                equiment_img.setVisibility(View.GONE);
            }



        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right:
                alert=0;
                new AlertView("上传图片", null, "取消", null,
                        new String[]{"拍照", "从相册中选择"},
                        this, AlertView.Style.ActionSheet, this).show();
                break;
            case R.id.jieshao_lay:

                if (jieState == 0) {
                    jieState = 1;
                    jieshao_nor.setImageResource(R.mipmap.up);
                    jieshao_detail.setVisibility(View.VISIBLE);

                } else {
                    jieState = 0;
                    jieshao_nor.setImageResource(R.mipmap.down);
                    jieshao_detail.setVisibility(View.GONE);
                }
                break;
            case R.id.jishu_lay:
                if (jishuState == 0) {
                    jishuState = 1;
                    jishu_nor.setImageResource(R.mipmap.up);
                    jishu_detail.setVisibility(View.VISIBLE);
                } else {
                    jishuState = 0;
                    jishu_nor.setImageResource(R.mipmap.down);
                    jishu_detail.setVisibility(View.GONE);
                }
                break;
            case R.id.shiyong_lay:

                if (shiyongState == 0) {
                    shiyongState = 1;
                    shiyong_nor.setImageResource(R.mipmap.up);
                    shiyong_detail.setVisibility(View.VISIBLE);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                handler.post(runnableUis);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }).start();
                } else {
                    shiyongState = 0;
                    shiyong_nor.setImageResource(R.mipmap.down);
                    shiyong_detail.setVisibility(View.GONE);
                }
                break;
            case R.id.yanghu_lay:
                if (yanghuState == 0) {
                    yanghuState = 1;
                    yanghu_nor.setImageResource(R.mipmap.up);
                    yanghu_detail.setVisibility(View.VISIBLE);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                handler.post(runnableUiss);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }).start();
                } else {
                    yanghuState = 0;
                    yanghu_nor.setImageResource(R.mipmap.down);
                    yanghu_detail.setVisibility(View.GONE);
                }
                break;
            case R.id.complain_click_area:
                if(NetWorkUtil.isWifi(context)){
                    if (!(deviceModel.getVideo() == null||deviceModel.getVideo().equals(""))) {
                        Intent intents = new Intent(Intent.ACTION_VIEW);
                        String type = "video/* ";
                        Uri uri = Uri.parse(deviceModel.getVideo());
                        intents.setDataAndType(uri, type);
                        startActivity(intents);
                    }
                }else{
                    alert=1;
                    new AlertView("提示", "当前状态3G/4G,是否要继续观看", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, this).setCancelable(true).show();
                }

                break;
            case R.id.shiyong_click_area:
                if(NetWorkUtil.isWifi(context)){
                    if (!(deviceModel.getUseVideo()== null||deviceModel.getUseVideo().equals(""))) {
                        Intent intents = new Intent(Intent.ACTION_VIEW);
                        String type = "video/* ";
                        Uri uri = Uri.parse(deviceModel.getUseVideo());
                        intents.setDataAndType(uri, type);
                        startActivity(intents);
                    }
                }else{
                    alert=2;
                    new AlertView("提示", "当前状态3G/4G,是否要继续观看", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, this).setCancelable(true).show();
                }

                break;
            case R.id.yanghu_click_area:
                if(NetWorkUtil.isWifi(context)){
                    if (!(deviceModel.getMaintenanceVideo()== null||deviceModel.getMaintenanceVideo().equals(""))) {
                        Intent intents = new Intent(Intent.ACTION_VIEW);
                        String type = "video/* ";
                        Uri uri = Uri.parse(deviceModel.getMaintenanceVideo());
                        intents.setDataAndType(uri, type);
                        startActivity(intents);
                    }
                }else{
                    alert=3;
                    new AlertView("提示", "当前状态3G/4G,是否要继续观看", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, this).setCancelable(true).show();
                }

                break;
        }
    }

    public void getData(final String refreshType) {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            jsondata.put("pageNum", pageNum);
            jsondata.put("pageSize", pageSize);
            parmas.put("jsonText", jsondata.toString());
        } catch (JSONException e) {

        }
        DeviceListervice.deviceList(context, parmas, new ResponseCallback<DeviceModelResult>() {
            @Override
            public void onSuccess(DeviceModelResult deviceModelResult) {

                switch (refreshType) {
                    case "1":
                        list.clear();
                        list.addAll(deviceModelResult.getList());
                        if (deviceModelResult.getList().size() <= pageSize) {
                            vlist.removeFooterView();
                            vlist.setPullLoadEnable(false);
                        } else {
                            vlist.showFooterView();
                            vlist.setPullLoadEnable(true);
                        }
                        break;
                    case "2":
                        list.addAll(deviceModelResult.getList());
                        if (deviceModelResult.getList().size() <= pageSize) {
                            vlist.removeFooterView();
                            vlist.setPullLoadEnable(false);
                        }
                        break;
                }
                equipmentListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }

    AdapterView.OnItemClickListener clickItem = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            Intent aboutIntent = new Intent(MyEquipmentDetailActivity.this, MyEquipmentDetailActivity.class);
            aboutIntent.putExtra("title", "系统消息");
            aboutIntent.putExtra("show", "2");
            startActivity(aboutIntent);
        }

    };
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面
            if (!(deviceModel.getVideo() == null || deviceModel.getVideo().equals(""))) {
                complain_click_area.setVisibility(View.VISIBLE);
                Bitmap bimp = FileUtils
                        .createVideoThumbnail(deviceModel.getVideo(), 80,
                                80);
                if (bimp != null) {
                    complain_add_video
                            .setVisibility(View.VISIBLE);
                    complain_status_btn.setVisibility(View.VISIBLE);
                    complain_add_video
                            .setImageBitmap(bimp);
                }

            } else {
                complain_click_area.setVisibility(View.GONE);
            }

        }

    };
    Runnable runnableUis = new Runnable() {
        @Override
        public void run() {
            //更新界面
            if (!(deviceModel.getUseVideo() == null || deviceModel.getUseVideo().equals(""))) {
                Bitmap bimp = FileUtils
                        .createVideoThumbnail(deviceModel.getUseVideo(), 80,
                                80);
                if (bimp != null) {
                    shiyong_click_area.setVisibility(View.VISIBLE);
                    shiyong_add_video
                            .setVisibility(View.VISIBLE);
                    shiyong_status_btn.setVisibility(View.VISIBLE);
                    shiyong_add_video
                            .setImageBitmap(bimp);
                } else {
                    shiyong_click_area.setVisibility(View.GONE);
                }
            }else{
                shiyong_click_area.setVisibility(View.GONE);
            }
        }

    };
    Runnable runnableUiss = new Runnable() {
        @Override
        public void run() {
            //更新界面
            if (!(deviceModel.getUseVideo() == null || deviceModel.getUseVideo().equals(""))) {
                Bitmap bimp = FileUtils
                        .createVideoThumbnail(deviceModel.getMaintenanceVideo(), 80,
                                80);
                if (bimp != null) {
                    yanghu_click_area.setVisibility(View.VISIBLE);
                    yanghu_add_video
                            .setVisibility(View.VISIBLE);
                    yanghu_status_btn.setVisibility(View.VISIBLE);
                    yanghu_add_video
                            .setImageBitmap(bimp);
                } else {
                    yanghu_click_area.setVisibility(View.GONE);
                }
            }else{
                yanghu_click_area.setVisibility(View.GONE);
            }
        }

    };
    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        Message msg = new Message();
        msg.obj = result.getImages();
        handlers.sendMessage(msg);


    }
    @Override
    public void onItemClick(Object o, int position) {
        //判断是否是拓展窗口View，而且点击的是非取消按钮
        if(alert==0) {
            if (position == 1) {
                CustomHelper.onClick(getTakePhoto(), position);
            } else if (position == 0) {
                CustomHelper.onClick(getTakePhoto(), position);
            }
        }else if(alert==1){
            if (!(deviceModel.getVideo() == null==deviceModel.getVideo().equals(""))) {
                Intent intents = new Intent(Intent.ACTION_VIEW);
                String type = "video/* ";
                Uri uri = Uri.parse(deviceModel.getVideo());
                intents.setDataAndType(uri, type);
                startActivity(intents);
            }
        }else if(alert==2){
            if (!(deviceModel.getUseVideo()== null||deviceModel.getUseVideo().equals(""))) {
                Intent intents = new Intent(Intent.ACTION_VIEW);
                String type = "video/* ";
                Uri uri = Uri.parse(deviceModel.getUseVideo());
                intents.setDataAndType(uri, type);
                startActivity(intents);
            }
        }else if(alert==3){
            if (!(deviceModel.getMaintenanceVideo()== null||deviceModel.getMaintenanceVideo().equals(""))) {
                Intent intents = new Intent(Intent.ACTION_VIEW);
                String type = "video/* ";
                Uri uri = Uri.parse(deviceModel.getMaintenanceVideo());
                intents.setDataAndType(uri, type);
                startActivity(intents);
            }
        }

    }
    Handler handlers = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            imgList = (ArrayList<TImage>) msg.obj;
            if (imgList != null) {
                try {

                    new UploadHelper().asyncPutObjectFromLocalFile(context, Constant.endpoint, imgList.get(0).getCompressPath(), new UploadCallback<Integer>() {
                        @Override
                        public void onRequestBefore() {

                        }

                        @Override
                        public void onFailure(PutObjectRequest response, String failureMsg, int code) {

                        }

                        @Override
                        public void onSuccess(PutObjectRequest response, Integer o) {
                            if(o==200){
                                logo="https://"+Constant.testBucket+Constant.enp+"/"+Constant.uploadObject;
                                updateUser();
                            }
                        }
                        @Override
                        public void onError(PutObjectRequest response, int errorCode, Exception e) {

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    };
    public void updateUser() {
        try {
            Map<String, Object> parmas = new HashMap<>();
            parmas.put("device_type", Constant.device_type);
            parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
            JSONObject jsondata = new JSONObject();
            if(!(logo==null||logo.equals(""))) {
                jsondata.put("deviceLogo", logo);
            }
            jsondata.put("id", deviceModel.getId());
            parmas.put("jsonText", jsondata.toString());
            MyService.deviceUpdateImg(context, parmas, new ResponseCallback<Map>() {
                @Override
                public void onSuccess(Map userinfoModel) {
                    finish();
                }

                @Override
                public void onError(Response response, int errorCode, String errorMsg, Exception e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
